package net.asrsmid.sample.adventureanalyzer.service;

import java.util.List;

import org.olap4j.metadata.Member;

import com.google.gson.Gson;

import net.asrsmid.config.AsRsAuthenticator;
import net.asrsmid.config.AsRsConfig;
import net.asrsmid.connection.AsRsApplicationPool;
import net.asrsmid.connection.as.AsOlapConnection;
import net.asrsmid.connection.rs.RsWebserviceProxy;
import net.asrsmid.invoker.AsOlapInvoker;
import net.asrsmid.invoker.RsWebserviceInvoker;
import net.asrsmid.sample.adventureanalyzer.json.AxisElement;

public class AdventureAnalyzerService {
	protected static final String AS_APP_ID = "ADVENTURE_ANALYZER";
	protected static final String RS_APP_ID = "ADVENTURE_ANALYZER";
	
	protected AsRsApplicationPool pool;
	
	public AdventureAnalyzerService(AsRsApplicationPool pool) {
		this.pool = pool;
	}
	
	protected AsOlapInvoker getAsOlapInvoker() {
		return new AsOlapInvoker(pool.getAsOlapConnection(AS_APP_ID));
	}
	
	protected RsWebserviceInvoker getRsWebserviceInvoker() {
		return new RsWebserviceInvoker(pool.getRsWebserviceProxy(RS_APP_ID));
	}
	
	protected AsOlapConnection getAsOlapConnection() {
		return pool.getAsOlapConnection(AS_APP_ID);
	}
	
	protected RsWebserviceProxy getRsWebserviceProxy() {
		return pool.getRsWebserviceProxy(RS_APP_ID);
	}
	
	protected AsRsConfig getConfig() {
		return pool.getConfig();
	}
	
	protected AsRsAuthenticator getRsAuthenticator() {
		return pool.getConfig().getRsAuthenticator(RS_APP_ID);
	}
	
	protected AsRsAuthenticator getAsAuthenticator() {
		return pool.getConfig().getAsAuthenticator(RS_APP_ID);
	}
	
	protected String getRsReportPath(String reportName) {
		return pool.getConfig().getReport(RS_APP_ID, reportName).getServerPath();
	}
	
	public String getAxisMembers(String axis) {
		String axisElmsStr = null;
		AsOlapConnection asConn = null;
		try {
			asConn = this.getAsOlapConnection();
			
			String vals[] = axis.split("\\.");
			String cubeName = pool.getConfig().getAsApplication(AS_APP_ID).getCubeName();
			String dimensionName = vals[0].substring(1, vals[0].length() - 1);
			String hierarchyName = vals[1].substring(1, vals[1].length() - 1);
			String levelName = hierarchyName;
			if (vals.length > 2)
				levelName = vals[2].substring(1, vals[2].length() - 1);
			
			// axis elements
			List<Member> members = asConn.getMembers(cubeName, dimensionName, hierarchyName, levelName);
			AxisElement[] axisElms = new AxisElement[members.size()];
			for (int i = 0; i < members.size(); i++) {
				Member m = members.get(i);
				axisElms[i] = new AxisElement(m.getUniqueName(), m.getCaption());
			}
			
			// to json
			Gson gson = new Gson();
			axisElmsStr = gson.toJson(axisElms);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (asConn != null) asConn.release();
		}

		return axisElmsStr;
	}
}
